from functools import wraps
from rest_framework import status
from rest_framework.response import Response

from .models import UserModel
from OA_django.settings import SECRET_KEY

import datetime
import jwt
import json


# 生成token
class MyJwt:

    def encode_time(self,userinfo):
        payload = {
            "exp": int((datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24)).timestamp()),
            'data': userinfo
        }
        encodeed_jwt = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

        return encodeed_jwt

    # 生成token
    def encode(self,userinfo):

        encoded_jwt = jwt.encode(userinfo, SECRET_KEY, algorithm='HS256')

        return encoded_jwt

    # 解密方法
    def decode(self,token):

        decoded_json = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])

        return decoded_json

# 用户鉴权 校验token
def jwt_auth(func):

    @wraps(func)
    def wrapper(self,request,*args,**kwargs,):

        token = request.headers.get('token',None)

        if not token:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'token不存在'})
        myjwt = MyJwt()
        try:
            user = myjwt.decode(token)
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': 'token不合法'})
        try:
            users = UserModel.objects.filter(id = user['id']).first()
            self._cuser = users
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '该用户不存在'})
        return func(self,request,*args,**kwargs)

    return wrapper